<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Route,URL;
use Config;

class AdminAuthMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null) 
    {   
        print_r(111);exit;
        Config::set('cache.default','array');
        if (Auth::guard($guard)->guest()) { 
            if ($request->ajax() || $request->wantsJson()) { 
                return response('Unauthorized.', 401); 
            } else { 

                return redirect()->guest('admin/login'); 
            } 
        }

        if(Auth::guard('admin')->user()->id === 1){
            return $next($request);
        }

        $previousUrl = URL::previous();
        
        if(!Auth::guard('admin')->user()->can(Route::currentRouteName())) {
            if($request->ajax() && ($request->getMethod() != 'POST')) {
                return response()->json([
                    'status' => -1,
                    'code' => 403,
                    'msg' => '您没有权限执行此操作'
                ]);
            } else {
                return response()->view('admin.errors.403', compact('previousUrl'));
            }
        }

        return $next($request); 
    } 
}
